package com.ruoyi.aitcommon.api;

import com.ruoyi.aitcommon.utils.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ApiLog;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/ait/common/restoper")
public class RestOperation {
	@Resource
	private AuthenticationManager authenticationManager;
	@Autowired
	private TokenService tokenService;

	/**
	 * <pre>
	 * post接口跳转
	 * 按照url调用接口
	 * body,head按照字符串格式传入
	 * jsonstr格式：
	 {
	 "url": "http://localhost:8080/ait/common/dboper/AITQuery",
	 "body":"{\"table\":\"ait_log\",\"path\":\"id=21610\"}",
	 "head":"{\"token\":\"token\"}"
	 }
	 * 
	 * </pre>
	 * @param jsonstr
	 * @return url接口返回值
	 */
	@ApiLog("post接口跳转")
	@PostMapping("/post")
	public JSONObject post(@RequestBody String jsonstr) {
		try {
			if (StringUtils.isBlank(jsonstr))
				throw new Exception("传入参数为空");

			JSONObject json=JSONUtils.parseObject(jsonstr);
			String url=json.getString("url");
			ObjUtils.checkBlank(url,"url必填");
			String body=json.getString("body");
			String head=json.getString("head");
			Map<String,Object> headmap=null;
			if(ObjUtils.isNotBlank(head)){
				headmap=JSONObject.parseObject(head, Map.class);
			}
			String ret = RestServiceUtils.post(url,headmap, body);
			return JSONResult.success("执行成功",ret);
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage());
		}
	}

	/**
	 * post接口跳转
	 * 在Head中添加跳转url
	 * @param jsonstr
	 * @return
	 */
	@ApiLog("post接口跳转")
	@PostMapping("/post2")
	public String post2(@RequestHeader Map<String, Object> headers, @RequestBody String jsonstr) {
		try {
			if (StringUtils.isBlank(jsonstr))
				throw new Exception("传入参数为空");
			if(ObjUtils.isBlank(headers))
				throw new Exception("传入Header为空");
			final Object url = headers.get("url");
			if(ObjUtils.isBlank(url))
				throw new Exception("传入Header.url为空");
//			调用接口
			String ret = RestServiceUtils.post(url.toString(),headers, jsonstr);
			return ret;
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage()).toJSONString();
		}
	}

	@ApiLog("获取token")
	@PostMapping("/token")
	public JSONObject getToken(@RequestBody String jsonstr) {
		try {
			if (StringUtils.isBlank(jsonstr))
				throw new Exception("传入参数为空");
			JSONObject json=JSONUtils.parseObject(jsonstr);
			String user=json.getString("user");
			String password=json.getString("password");

//			白名单设置参考 com.ruoyi.framework.config.SecurityConfig.configure
//			参考代码 com.ruoyi.framework.web.service.SysLoginService.login
			/**
			 * 同登录方法的区别:
			 * 去掉验证码处理
			 * 去掉登录日志
			 */

			// 用户验证
			Authentication authentication = authenticationManager
						.authenticate(new UsernamePasswordAuthenticationToken(user, password));
			LoginUser loginUser = (LoginUser) authentication.getPrincipal();
			// 生成token
			final String token = tokenService.createToken(loginUser);
			// 返回token
			return JSONResult.success("执行成功",token);
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage());
		}
	}
}
